package JDBC;

import util.JDBCUtils;

import java.sql.*;
import java.util.Scanner;

/**
 * @Author: ylc
 * @Description:登录案例,PreparedStatement对象的使用
 * @Date Created in 2022-05-10 13:35
 */
public class JDBCDemo3 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名：");
        String username = sc.nextLine();
        System.out.println("请输入密码：");
        String password = sc.nextLine();

        boolean flag = new JDBCDemo3().login(username, password);
        if(flag){
            System.out.println("登录成功！");
        }else{
            System.out.println("用户名密码错误！");
        }

    }

    /**
     * 登录方法
     * @param username
     * @param password
     * @return
     */
    public boolean login(String username, String password){
        if(username == null || password == null){
            return false;
        }
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            conn = JDBCUtils.getConnection();
            stmt = conn.createStatement();
            //此处会出现SQL注入问题，需使用PreparedStatement对象来解决
            String sql = "select * from user where username = '"+username+"' and password = '"+password+"'";

            rs = stmt.executeQuery(sql);
            return rs.next();//如果有下一行，说明数据库中存在该数据，返回true
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtils.close(rs,stmt,conn);
        }
        return false;
    }

    /**
     * 登录方法,使用PreparedStatement实现
     * @param username
     * @param password
     * @return
     */
    public boolean login2(String username ,String password){
        if(username == null || password == null){
            return false;
        }
        //连接数据库判断是否登录成功
        Connection conn = null;
        PreparedStatement pstmt =  null;
        ResultSet rs = null;
        //1.获取连接
        try {
            conn =  JDBCUtils.getConnection();
            //2.定义sql
            String sql = "select * from user where username = ? and password = ?";
            //3.获取执行sql的对象
            pstmt = conn.prepareStatement(sql);
            //给?赋值
            pstmt.setString(1,username);
            pstmt.setString(2,password);
            //4.执行查询,不需要传递sql
            rs = pstmt.executeQuery();
            //5.判断
            return rs.next();//如果有下一行，则返回true

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.close(rs,pstmt,conn);
        }
        return false;
    }

}
